package com.example.stlink.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.stlink.R;
import com.example.stlink.configs.adapter.TeaDeleteCourseAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.activitys.fragmentChild.activityTeaCourse.CourseDetail;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * 已完成课表
 */
public class CrsFinishedListFragment extends Fragment {

    private static RecyclerView lvFinishedCourseList;
    private static List<Course> coursesData;
    private static TeaDeleteCourseAdapter adapter;
    private static AppCompatActivity mAppCompatActivity;
    private static SwipeRefreshLayout srlMyRefresh;

    private int mPage = 1;
    private int mCurrentColIndex = 0;

    private static Bundle bundle;
    private static Handler handler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_course_finished, container, false);
        initView(view);
        return view;
    }

    /**
     * 堆外暴露的一个方法，用于获取该碎片实例
     * @param str 说明
     * @param appCompatActivity 上下文
     * @return 未结课的碎片实例
     */
    public static CrsFinishedListFragment newInstance(String str, AppCompatActivity appCompatActivity){
        CrsFinishedListFragment unfinishedFra = new CrsFinishedListFragment();
        mAppCompatActivity = appCompatActivity;
        return unfinishedFra;
    }


    /**
     * 绑定控件，初始化实例等
     * @param view 当前视图
     */
    private void initView(View view) {

        lvFinishedCourseList = view.findViewById(R.id.lv_finished_course_list);
        srlMyRefresh = view.findViewById(R.id.srl_my_refresh);
        srlMyRefresh.setColorSchemeColors(Color.parseColor("#ff0000"),Color.parseColor("#00ff00"));

        refreshData();

    }

    public static void refreshData(){

        coursesData = new ArrayList<>();
        adapter = new TeaDeleteCourseAdapter(
                mAppCompatActivity,
                R.layout.card_course_tea,
                coursesData,
                1
        );
        LinearLayoutManager llm = new LinearLayoutManager(mAppCompatActivity);
        lvFinishedCourseList.setLayoutManager(llm);
        lvFinishedCourseList.setAdapter(adapter);

        bundle = mAppCompatActivity.getIntent().getExtras();
        handler = new Handler(Looper.getMainLooper()){
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                CourseData courseData = (CourseData) msg.obj;
                coursesData.addAll(courseData.getRecords());
                adapter.notifyDataSetChanged();
            }
        };
        getUnfinishedCourseList();

        setListener();
    }

    /**
     * 添加点击事件
     */
    public static void setListener(){
        adapter.setOnItemClickListener(new onRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                Intent intent = new Intent(mAppCompatActivity, CourseDetail.class);
                bundle = mAppCompatActivity.getIntent().getExtras();
                //将position传入bundle
                Long courseId = coursesData.get(position).getmCourseId();
                bundle.putLong(ModelFieldConstants.COURSE_ID, courseId);
                System.out.println("courseId == " + courseId);
                System.out.println("course == " + coursesData.get(position));
                System.out.println("bundle:courseId == " + bundle.getLong(ModelFieldConstants.COURSE_ID));
                System.out.println("bundle:userId == " + bundle.getLong(ModelFieldConstants.USER_ID));
                intent.putExtras(bundle);
                mAppCompatActivity.startActivity(intent);
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) { }
        });
        srlMyRefresh.setOnRefreshListener(() -> {
            refreshData();
            srlMyRefresh.setRefreshing(false);
        });
    }

    private static void getUnfinishedCourseList(){
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID);
            final String url = UrlConstants.TEACHER_FINISHED + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        System.out.println("courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<Course> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<Course>>() {}.getType());

                        System.out.println("courseData = " + courseData);

                        if(courseData != null){
                            Message message = new Message();
                            message.obj = courseData;
                            handler.sendMessage(message);
                        }else{
                            System.out.println("courseData: null " + "...............................");
                        }
                    }
                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }

}
